Why is reading lines from stdin much slower in C++ than in Python?
Why is reading lines from stdin much slower in C++ than in Python?
350
07-Jul-2023
Updated on 10-Jul-2023
Aryan Kumar
10-Jul-2023There are a few reasons why reading lines from stdin is much slower in C++ than in Python.
readline()function in Python is a built-in function that is specifically designed to read lines from stdin. Thereadline()function in C++ is not a built-in function, and it is implemented using thestd::cinobject. Thestd::cinobject is a general-purpose input stream that can be used to read data from a variety of sources, including stdin. However, thestd::cinobject is not as efficient as thereadline()function in Python.readline()function in Python is multithreaded, which means that it can read lines from stdin in parallel. Thestd::cinobject in C++ is not multithreaded, which means that it can only read lines from stdin sequentially.readline()function in Python is optimized for reading lines from stdin. Thestd::cinobject in C++ is not optimized for reading lines from stdin.As a result of these factors, the
readline()function in Python is much faster than thestd::cinobject in C++.Here is an example of how to read lines from stdin in Python and C++:
Python
C++
The Python code will read lines from stdin and print them to the console. The C++ code will also read lines from stdin and print them to the console. However, the Python code will be much faster than the C++ code.